#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______   _______   _______  #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \ |       \ |   ____|  #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  ||  .--.  ||  |__      #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  ||  |  |  ||   __|      #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  ||  '--'  ||  |____      #
#|__|     | _| `._____||_______||_______| \______| \______/ |_______/ |_______|    #
#                                                                                 #
#                                Import Core                                     #
#                             Circuits FrameWork                                #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Imports
from glob import glob
from circuits.core import listener, Event, Component

# Sets plugin variables
__id__ = "importsys"
__core__ = True

# Creates event classes
class PluginLoad(Event): pass
class PluginUnload(Event): pass
class IRCmessage(Event): pass

class Import(Component):

	def __init__(self, *args, **kwargs):
		# Important: Call the super constructors to initialize the Component.
		super(Network, self).__init__(*args, **kwargs)
		self.channel = kwargs["channel"]
	
	# Load modules	
	@listener("command-load")
	def loadmodule(self, **kwargs):
		# Checks for botadmin permissions
		if kwargs["botadmin"]:
			
			# Checks for proper arguments
			if len(kwargs["command"]) > 1:
				
				# Checks for proper import file
				if '-' in kwargs["command"][1]:
					folder = kwargs["command"][1].split('-')[0].lower()
					plugin = kwargs["command"][1].split('-')[1].lower()
			
					# Checks if file exists
					modules = glob("%s/*.py" % (folder))
					if "%s/%s.py" % (folder, plugin)) in modules:
						
						# Imports the module
						module = __import__("%s/%s" % (folder, plugin))
						mod = module.startup()
						self.push(PluginLoad(mod[0], mod[1]), "plugin-load", self.channel)
						
						# Replies module imported
						self.push(IRCmessage(kwargs["destination"], "%s has expanded my tiny brain." % (plugin)), "issue-message", self.channel)
				
					# Replies does not exist	
					else:
						self.push(IRCmessage(kwargs["destination"], "%s doesn't exist." % (plugin)), "issue-message", self.channel)
				
				# Replies invalid command		
				else:
					self.push(IRCmessage(kwargs["destination"], "Your command is confusing. Please use this syntax: load <folder>-<plugin>."), "issue-message", self.channel)
			
			# Replies not enough information
			else:
				self.push(IRCmessage(kwargs["destination"], "More info plzkthnxbia."), "issue-message", self.channel)
		
		# Replies not bot admin
		else:
			self.push(IRCmessage(kwargs["destination"], "You are not a bot administrator."), "issue-message", self.channel)
	
	# Unloads modules	
	@listener(command-unload")
	def unloadmodule(self, **kwargs):
		# Checks for botadmin permissions
		if kwargs["botadmin"]:
			
			# Checks for proper arguments
			if len(kwargs["command"]) > 1:
				
				# Checks for proper import file
				if '-' in kwargs["command"][1]:
					folder = kwargs["command"][1].split('-')[0].lower()
					plugin = kwargs["command"][1].split('-')[1].lower()
			
					# Checks if file exists
					modules = glob("%s/*.py" % (folder))
					if "%s/%s.py" % (folder, plugin)) in modules:
						
						# Unimports the module if module is not core
						module = __import__("%s/%s" % (folder, plugin))
						if module.__core__ == False
							self.push(PluginLoad(mod[0], mod[1]), "plugin-unload", self.channel)
						
							# Replies module unimported
							self.push(IRCmessage(kwargs["destination"], "%s has been forgotten." % (plugin)), "issue-message", self.channel)
				
						# Replies module is core
						else:
							self.push(IRCmessage(kwargs["destination"], "You want to unload my what!?!?!? How bout I just unload your liver?"), "issue-message", self.channel)
				
					# Replies does not exist	
					else:
						self.push(IRCmessage(kwargs["destination"], "%s doesn't exist." % (plugin)), "issue-message", self.channel)
				
				# Replies invalid kwargs["command"]		
				else:
					self.push(IRCmessage(kwargs["destination"], "Your command is confusing. Please use this syntax: unload <folder>-<plugin>."), "issue-message", self.channel)
			
			# Replies not enough information
			else:
				self.push(IRCmessage(kwargs["destination"], "More info plzkthnxbia."), "issue-message", self.channel)
		
		# Replies not bot admin
		else:
			self.push(IRCmessage(kwargs["destination"], "You are not a bot administrator."), "issue-message", self.channel)
	
	# Reload modules	
	@listener("command-reload")
	def reloadmodule(self, **kwargs):
		# Checks for botadmin permissions
		if kwargs["botadmin"]:
			
			# Checks for proper arguments
			if len(kwargs["command"]) > 1:
				
				# Checks for proper import file
				if '-' in kwargs["command"][1]:
					folder = kwargs["command"][1].split('-')[0].lower()
					plugin = kwargs["command"][1].split('-')[1].lower()
			
					# Checks if file exists
					modules = glob("%s/*.py" % (folder))
					if "%s/%s.py" % (folder, plugin)) in modules:
						
						# Unimports the module
						module = __import__("%s/%s" % (folder, plugin))
						self.push(PluginLoad(module), "plugin-unload", self.channel)
						
						# Refreshes cache
						reload(module)
						
						# Imports the module
						self.push(PluginLoad(module), "plugin-load", self.channel)
						
						# Replies module imported
						self.push(IRCmessage(kwargs["destination"], "%s has expanded my tiny brain." % (plugin)), "issue-message", self.channel)
				
					# Replies does not exist	
					else:
						self.push(IRCmessage(kwargs["destination"], "%s doesn't exist." % (plugin)), "issue-message", self.channel)
				
				# Replies invalid command		
				else:
					self.push(IRCmessage(kwargs["destination"], "Your command is confusing. Please use this syntax: load <folder>-<plugin>."), "issue-message", self.channel)
			
			# Replies not enough information
			else:
				self.push(IRCmessage(kwargs["destination"], "More info plzkthnxbia."), "issue-message", self.channel)
		
		# Replies not bot admin
		else:
			self.push(IRCmessage(kwargs["destination"], "You are not a bot administrator."), "issue-message", self.channel)
		
def startup(channel, cursor):
	plugin = Import(channel = channel, cursor = cursor)
	return (__id__, plugin)

def kill():
	return __id__
